package com.example.shopping.security;

import com.example.shopping.entity.User;
import com.example.shopping.mapper.RoleMapper;
import com.example.shopping.mapper.UserMapper;
import com.example.shopping.mapper.UserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 功能：
 * 作者：张赛特
 * 日期：2025/11/17 16:59
 */
@Service
@Transactional
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user =userMapper.getUserByPhone(username);
        if (Objects.isNull(user)){
            throw new UsernameNotFoundException(username);
        }
        List<String> roleNameList=new ArrayList<>();
        List<String> permissionNameList=new ArrayList<>();

        userRoleMapper.getUserRolesByUserId(user.getUserId());

        return new LoginUserDetails(user,roleNameList,permissionNameList);
    }
}